package com.example.exam.servlet;

import com.example.exam.dao.ExamDAO;
import com.example.exam.dao.ScoreDAO;
import com.example.exam.entity.Exam;
import com.example.exam.entity.Student;
import com.example.exam.entity.Score;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 仪表盘Servlet
 */
@WebServlet("/dashboard")
public class DashboardServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private ExamDAO examDAO = new ExamDAO();
    private ScoreDAO scoreDAO = new ScoreDAO();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("student") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        // 获取学生ID
        String studentId = ((Student) session.getAttribute("student")).getStudentId();
        
        // 获取即将进行的考试
        List<Exam> upcomingExams = examDAO.getAvailableExams(studentId);
        request.setAttribute("upcomingExams", upcomingExams);
        
        // 获取最近的成绩
        List<Score> recentScores = scoreDAO.getScoresByStudentId(studentId);
        request.setAttribute("recentScores", recentScores);

        // ---- 将计算逻辑从JSP移动到Servlet ----
        request.setAttribute("upcomingExamsCount", upcomingExams != null ? upcomingExams.size() : 0);
        
        if (recentScores != null && !recentScores.isEmpty()) {
            // 计算已完成的考试数
            long completedExamsCount = recentScores.size();
            request.setAttribute("completedExamsCount", completedExamsCount);

            // 计算挂科数 (分数 < 60)
            long failedExamsCount = recentScores.stream()
                    .filter(score -> score.getScore() < 60)
                    .count();
            request.setAttribute("failedExamsCount", failedExamsCount);
            
            // 计算平均分
            double totalScore = recentScores.stream()
                    .mapToDouble(Score::getScore)
                    .sum();
            double averageScore = totalScore / completedExamsCount;
            request.setAttribute("averageScore", averageScore);

        } else {
            request.setAttribute("completedExamsCount", 0);
            request.setAttribute("failedExamsCount", 0);
            request.setAttribute("averageScore", 0.0);
        }
        // ---- 计算逻辑结束 ----
        
        // 转发到仪表盘页面
        request.getRequestDispatcher("/WEB-INF/views/dashboard.jsp").forward(request, response);
    }
}    